package org.elucid.chess.piece;

import java.util.ArrayList;
import java.util.List;

import org.elucid.chess.model.Board.Direction;
import org.elucid.chess.model.Game;
import org.elucid.chess.model.Move;
import org.elucid.chess.model.Piece;
import org.elucid.chess.model.Square;

/**
 * 
 * @author george
 *
 */
public class Knight extends Piece {

	/**
	 * 
	 * @param isWhite
	 */
	public Knight(boolean isWhite) {
		super(isWhite);
	}

	@Override
	public List<Move> listLegalMoves(Game game, boolean isOnlyThreats) {
		List<Move> legalMoves = new ArrayList<Move>();

		Square fromSquare = game.getPieceSquares().get(this);

		// there are eight possible moves for a Knight
		addIfLegal(fromSquare, game, Direction.North, Direction.East, legalMoves);
		addIfLegal(fromSquare, game, Direction.East, Direction.North, legalMoves);
		addIfLegal(fromSquare, game, Direction.North, Direction.West, legalMoves);
		addIfLegal(fromSquare, game, Direction.West, Direction.North, legalMoves);
		addIfLegal(fromSquare, game, Direction.South, Direction.East, legalMoves);
		addIfLegal(fromSquare, game, Direction.East, Direction.South, legalMoves);
		addIfLegal(fromSquare, game, Direction.South, Direction.West, legalMoves);
		addIfLegal(fromSquare, game, Direction.West, Direction.South, legalMoves);

		return legalMoves;
	}
	
	/**
	 * 
	 * @param fromSquare
	 * @param game
	 * @param longDirection
	 * @param shortDirection
	 * @param moveList
	 */
	private void addIfLegal(final Square fromSquare, final Game game, final Direction longDirection, final Direction shortDirection, final List<Move> moveList)
	{
		// there are eight possible moves for a Knight
		Square toSquare = game.getBoard().getSquareAt(fromSquare, longDirection, 2);
		if (toSquare != null) {
			toSquare = game.getBoard().getSquareAt(toSquare, shortDirection, 1);
        	if (toSquare != null) {
    			Piece piece = game.getPieceSquares().getKey(toSquare);
    			if ( piece == null || isOpponentsPiece(piece) )
    			{
    				Move move = new Move(fromSquare, toSquare,true);
    				moveList.add(move);
    			}
        	}
		}
	}


}
